<template>
  <div>
    <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>
    <div class="add">
      <div class="common-layout">
        <el-container>
          <el-main>
            <el-row>
              <el-col :span="24">
                <div class="grid-content ep-bg-purple">
                  <h4>基本信息</h4>
                  <el-form :inline="true" :model="buyPay" :rules="rules" status-icon ref="formRef">
                    <el-form-item label="单据编号" prop="code">
                      <el-input
                          v-model="buyPay.code"
                          style="width: 240px"
                          placeholder="请输入单据编号"
                          clearable
                          readonly
                      />
                    </el-form-item>

                    <el-form-item label="单据日期" prop="biliDate">
                      <el-date-picker
                          v-model="buyPay.biliDate"
                          type="date"
                          placeholder="请选择日期"
                          value-format="YYYY-MM-DD"

                      />
                    </el-form-item>
                    <!--                    :disabled-date="disabledDate"-->
                    <!-- 报价名称 -->
                    <el-form-item label="备注" prop="info">
                      <el-input
                          v-model="buyPay.info"
                          style="width: 240px"
                          placeholder="请输入备注名称"
                      />
                    </el-form-item>


                    <el-form-item label="供应商" prop="proId">
                      <el-select
                          v-model="buyPay.proId"
                          placeholder="请选择供应商"
                          style="width: 240px;"
                          clearable
                          filterable
                      >
                        <el-option
                            v-for="pro in proList"
                            :key="pro.id"
                            :label="pro.name"
                            :value="pro.id"
                        />
                      </el-select>
                    </el-form-item>

                    <el-form-item label="业务员" prop="uid">
                      <el-select
                          v-model="buyPay.uid"
                          placeholder="请选择业务员"
                          style="width: 240px;"
                          clearable
                      >
                        <el-option
                            v-for="thisUser in userList"
                            :key="thisUser.id"
                            :label="thisUser.name"
                            :value="thisUser.id"
                        />
                      </el-select>
                    </el-form-item>

                    <!-- 部门 -->
                    <el-form-item label="部门" prop="deptId">
                      <el-select
                          v-model="buyPay.deptId"
                          placeholder="请选择部门"
                          style="width: 240px;"
                          clearable
                          @change="loadUser();buyPay.uid = null"
                      >
                        <el-option
                            v-for="dept in departments"
                            :key="dept.value"
                            :label="dept.label"
                            :value="dept.value"
                        />
                      </el-select>
                    </el-form-item>




                    <el-form-item label="源单" prop="sourceCode">
                      <el-input
                          v-model="buyPay.sourceCode"
                          style="width: 240px"
                          placeholder="选择源单订单"
                          @click="querySource();searchForm.code='';"
                          readonly
                      />
                    </el-form-item>

                  </el-form>
                </div>
              </el-col>
            </el-row>
          </el-main>
        </el-container>
      </div>
    </div>
  </div>


  <!-- 退款信息表格 -->
  <div class="collection-info">
    <h4>付款账户</h4>
    <div class="toolbar">
      <el-button @click="addAccount()">继续添加</el-button>
    </div>
    <el-table :data="buyPayDetailList" border style="width: 100%">
      <el-table-column label="付款账户" align="center" width="150">
        <template #default="scope">
          <el-select
              v-model="scope.row.accountId"
              placeholder="请选择账户"
              clearable
          >
            <el-option
                v-for="account in payAccountList"
                :key="account.id"
                :label="account.account"
                :value="account.id"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="收款方式" align="center" width="150">
        <template #default="scope">
          <el-select
              v-model="scope.row.typeId"
              placeholder="请选择方式"
              clearable
          >
            <el-option
                v-for="method in payMethodList"
                :key="method.id"
                :label="method.payName"
                :value="method.id"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="收款金额" align="center" width="180">
        <template #default="scope">
          <el-input-number
              v-model="scope.row.amount"
              :min="0"
              :precision="2"
              controls-position="right"
              style="width: 160px"
              @input="calAccount(scope.row)"
              @focusout="calAccount(scope.row)"
          />
        </template>
      </el-table-column>

      <!--      <el-table-column label="手续费" align="center" width="150">-->
      <!--        <template #default="scope">-->
      <!--          <el-input-number-->
      <!--              v-model="scope.row.serviceAmount"-->
      <!--              :min="0"-->
      <!--              :precision="2"-->
      <!--              controls-position="right"-->
      <!--              style="width: 120px"-->
      <!--              @input="calAccount(scope.row)"-->
      <!--              @focusout="calAccount(scope.row)"-->
      <!--          />-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <el-table-column label="实际付款" align="center" width="120">
        <template #default="scope">{{ scope.row.amount }}</template>
      </el-table-column>

      <el-table-column label="付款备注" align="center">
        <template #default="scope">
          <el-input
              v-model="scope.row.info"
              placeholder="请输入备注"
              clearable
          />
        </template>
      </el-table-column>

    </el-table>

    <div class="total-summary">
      <div class="total-label">本次预付核销金额合计</div>
      <div class="total-amount">{{ payAmount }}</div>
      <div class="total-label">该订单代付总金额</div>
      <div class="total-amount">{{ maxAmount }}</div>
    </div>
  </div>

  <div class="dialog">
    <el-dialog
        v-model="dialog"
        title="采购入库单"
        width="70%"
        draggable
        top="5vh"
    >
      <!-- 查询条件区域 -->
      <div class="dialog-header">
        <el-input
            v-model="searchForm.code"
            placeholder="请输入单据编号"
            style="width: 240px;margin-right: 15px"
        />

        <el-button type="primary" icon="Search" @click="querySource()">查询</el-button>
        <el-button icon="Refresh" @click="searchForm.code = '';querySource()">重置</el-button>
      </div>


      <!-- 表格区域 -->
      <el-table
          ref="multipleTableRef"
          :data="sourceOrderList"
          row-key="id"
          style="width: 100%"
          height="60vh"
          @row-click="handleRowClick"
          highlight-current-row
      >
        <el-table-column prop="code" label="单据编号" width="300" />
        <el-table-column prop="providerName" label="供应商" width="200" />
        <el-table-column prop="businessmanName" label="业务员" width="120" />
      </el-table>

      <!-- 分页及操作按钮 -->
      <div class="dialog-footer">
        <!-- 分页组件 -->
        <div class="pagination-wrapper">
          <el-pagination
              background
              layout="prev, pager, next"
              :total="pageInfo.total"
              :page-size="PopupsPageSize"
              :current-page="PopupsPageNo"
              @current-change="handlePageChange"
          />
        </div>
        <div class="action-buttons">
          <el-button @click="dialog = false;buyPay.sourceCode='' ">关闭</el-button>
          <el-button type="primary" @click="dialog = false;">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>


</template>


<script setup lang="ts">
import { ref, reactive,withKeys ,watch,computed} from 'vue';
import BasicInformation from '@/public-view/BasicInformation.vue';
import {type ComponentSize, ElMessage, type FormInstance, type FormRules, type TableInstance} from 'element-plus'
import {ElInput, ElAutoResizer, ElTableV2} from 'element-plus'
import { useRouter,useRoute } from 'vue-router';
import axios from 'axios';
import type {PubUser} from "@/types/public-cg/User.ts";
import type { PageInfo} from "@/types/cg/Util.ts";
import type {PublicProvider} from "@/types/public-cg/provider.ts";

import type {CGUser, PayAccount, PayDetail, PayMethod} from "@/types/cw/Public.ts";
import type {BuyPay, BuyPayDetail} from "@/types/cw/BuyPay.ts";
import request from "@/util/request.ts";

let route = useRoute()
let router=useRouter()
let code = route.query.code

let dialog = ref(false)
let currentUser = reactive({
  uid:"1",
  userName:"admin",
})
let PopupsPageNo=ref(1)
let PopupsPageSize=ref(10)
let searchForm = reactive({
  code:"",
})
let uid = 2
let proList = ref<PublicProvider[]>([])



let userList = ref<CGUser[]>([
])

let payMethodList = ref<PayMethod[]>([])

let payAccountList = ref<PayAccount[]>([])

let sourceOrderList = ref([])


let pageInfo = ref<PageInfo>({
  pages:0,
  pageNum:PopupsPageNo.value,
  pageSize:PopupsPageSize.value,
  total:0,
  list:null,
})


const departments = ref([
  { value: 1, label: '生产部门' },
  { value: 2, label: '销售部门'},
  { value: 3, label: '仓管部门'},
  { value: 4, label: '采购部门'},
  { value: 5, label: '财务部门'},
  { value: 10, label: '人事部门'}
])



let buyPayDetailList=ref<BuyPayDetail[]>([{}])

let buyPay =ref<BuyPay>({
  id:0,
  code:'',
  sourceCode:'',
  sourceName:'',
  biliDate:null,
  uid:null,
  userName:'',
  deptId:null,
  deptName:'',
  proId:null,
  proName:'',

  info:'',
  status:0,
  statusStr:'',
  totalAmount:0,
  settleAmount:0,
  createId:0,
  modiId:0,
  type:26,
  list:null,
})


if(route.query.sourcecCode != null && ''){
  buyPay.value.sourceCode = route.query.sourceCode
  buyPay.value.proId = route.query.proId
}

let manager = ref<PubUser>({
  name:"testUser",
  dept:"采购部",
})






let title=ref('采购付款') //TODO 订单标题


let checkPassList = [1, 3 , 4 , 11]
// todo 监听按钮
const handleAction = (action:string) => {
  switch(action) {
    case 'save':
      if (checkPassList.includes(buyPay.value.status)) {
        ElMessage.error("单据无法修改");
        return;
      }
      if (code == null || ''){
        submit();
      }else {
        modi();
      }
      break
    case 'history':
      router.push('pay')
      break;
    case 'audit':
      break;
    case 'source':
      dialog.value = true;
  }
}

// todo  按钮配置
const mainActions = ref([
  {
    name: 'save',
    label: '保存',
    type: 'primary',
    icon: 'DocumentAdd'
  },
  {
    name: 'audit',
    label: '审核',
    hidden: true
  },
  {
    name:'source',
    label: "选择源单",
  },
  {
    name: 'history',
    label: '历史单据',
    badge: 3 // 角标数字
  }

])

const rules = ref({
  sourceCode:[{required:true , message:"请输入源单号",trigger:'blur'}],
  proId:[{required:true , message:"选择供应商",trigger:'change'}],
  uid:[{required:true , message:"选择用户",trigger:'change'}],
  deptId:[{required:true , message:"选择部门",trigger:'change'}],
})



function addAccount(){
  buyPayDetailList.value.push({})
}


// 只读列配置
const readonlyColumns = [
  { prop: 'taxAmount' , label: '税额'  ,width:150},
  { prop: 'taxPrice' , label: '应付金额' ,width: 200}
]



// 含税价计算

// TODO 计算金额
// 格式化金额显示


const calAccount = (row:any) => {
  if (row.amount && row.serviceAmount){
    row.total = (row.amount + row.serviceAmount).toFixed(2)
  }else if (row.amount){
    row.total = row.amount.toFixed(2)
  }
}
const payAmount = computed(() => {
  return buyPayDetailList.value.reduce((sum, row) => {
    const price = Number(row.amount) || 0
    return sum + (price)
  }, 0)
})

let maxAmount = ref(0)


// TODO 加载参数信息
async function loadInfo(){
  let methodRes = await request.post("cw/PaymentMethodController/selectPaymentMethod")
  payMethodList.value = methodRes.data.data
  // console.log(payMethodList.value)
  let accountRes = await request.post("basic/Account/selectAllAccount")
  payAccountList.value = accountRes.data.data

  // let payThingRes = await request.post("cw/getAllCostThing")
  // payThingList.value = payThingRes.data.data

  // let payOrderType = await request.post("cw/TKD/getRefundType")
  // payOrderTypeList.value = payOrderType.data.data

  let providerRes = await request.post("basic/Provider/selectProviderByPage",{
    "pageNo":1,
    "pageSize" : 100
  })
  proList.value = providerRes.data.data.list
  // console.log(proList.value)
}
loadInfo();
async function loadUser(){
  let userRes = await request.post("per/user/selectUserByDept",{
    "dept":buyPay.value.deptId
  })
  userList.value = userRes.data.data
}
loadUser()


function handlePageChange(newPage:number){
  alert("newPage")
  PopupsPageNo.value = newPage;
  querySource();
}

// 查询源单分页 TODO
async function querySource(){

  let res = await request.post("kc/inStore/getInStoreList",{
    "pageSize":PopupsPageSize.value,
    "pageNo":PopupsPageNo.value,
    "code":searchForm.code,
    "pid":buyPay.value.proId == 0 ? null : buyPay.value.proId  ,
    "typeId":"5",
  })
  dialog.value = true
  sourceOrderList.value = res.data.data.list;
  console.log("cgrk",res.data)
}

const multipleTableRef = ref<TableInstance>()
const currentRow = ref<any >(null)
const handleRowClick = (row: any) => {
  console.log("row" , row)
  if (currentRow.value?.code === row.code) {
    // 如果点击的是当前选中的行，取消选中
    currentRow.value = null
    multipleTableRef.value?.setCurrentRow(null)
    buyPay.value.sourceCode = ''
    buyPayDetailList.value.length = 0
  } else {
    // 否则，选中当前行
    currentRow.value = row
    buyPay.value.sourceCode = row.code
    buyPay.value.proId = row.pid
    multipleTableRef.value?.setCurrentRow(row)
    maxAmount.value = row.inStoreSumPrice
    // tableData.value = row.list
  }
}



let formRef = ref<FormInstance>()
async function submit() {
  const formValid = await formRef.value?.validate()
  if (!formValid) return
  console.log("buyPay:",buyPay)
  if (payAmount.value > maxAmount.value){
    alert("付款金额超过入库金额")
    return;
  }
  buyPay.value.createId = uid
  buyPay.value.list = buyPayDetailList.value
  buyPay.value.totalAmount = payAmount.value
  buyPay.value.settleAmount = 0
  console.log(buyPay.value)
  let res = await request.post("cw/CGFK/addBuyPay", buyPay.value)
  console.log(res.data)
  if (res.data.code == 200){
    router.push('pay')
  }
}



async function getCGFK(){
  let res = await request.post("cw/CGFK/getBuyPay",{
    "code":code
  })
  console.log(res.data)
  buyPay.value = res.data.data
  buyPayDetailList.value = res.data.data.list

}

if (code == null || ''){
  // todo 可获取编码
}else {
  getCGFK()
}


async function modi(){
  const formValid = await formRef.value?.validate()
  if (!formValid) return
  buyPay.value.modiId = uid
  buyPay.value.list = buyPayDetailList.value
  buyPay.value.totalAmount = payAmount.value
  buyPay.value.settleAmount = 0
  console.log(buyPay.value)
  let res = await request.post("cw/CGFK/modiBuyPay", buyPay.value ,)
  if (res.data.code == 200){
    router.push('pay')
  }

}


// async function loadData(){
//   console.log("loadData cgrk_code:", buyPay.value.sourceCode)
//   if (buyPay.value.sourceCode ==''){
//     return
//   }else {
//     let res = await request.post("kc/inStoreDetail/getInStoreDetailList", null,{
//       params:{
//         "inStoreCode":buyPay.value.sourceCode,
//       }
//     })
//     buyPayDetailList.value = res.data.data.map(item=>({
//       id:item.id,
//       code:item.code,
//       proId:item.pid,
//
//     }))
//     console.log("table",buyPayDetailList.value)
//     console.log("res",res.data.data)
//   }
// }


</script>

<style scoped>
:deep(.el-table__body tr.current-row>td.el-table__cell) {
  background-color: #1890FF;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.required-label::after {
  content: "*";
  color: #f56c6c;
  margin-left: 4px;
}

.goods-table {
  margin-top: 20px;
}

.toolbar {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.el-table :deep(.el-input__inner) {
  text-align: center;
}
.total-summary {
  background: #fff8dc; /* 浅黄色背景 */
  padding: 12px 20px;
  display: flex;
  justify-content: flex-end;
  border: 1px solid #ebeef5;
  border-top: none;
}

.total-label {
  font-weight: 600;
  color: #606266;
  margin-right: 30px;
}

.total-amount {
  color: #f56c6c;
  min-width: 120px;
  text-align: right;
  font-family: Arial, sans-serif;
}
.action-buttons button{
  width: 200px;
  display: inline-block;
  margin: auto 100px;
}
.action-buttons{
  display: flex;
  flex-direction: row-reverse;
  padding: 0 30%;
}
.pagination-wrapper{
  margin: 0 auto;
  width: 200px;
}
.collection-info {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.source-info {
  margin-top: 20px;
  border-top: 2px solid #ebeef5;
  padding-top: 15px;
}
.total-summary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 15px;
  padding: 10px;
  background: #f4f4f5;
  border-radius: 4px;
}

.total-label {
  font-weight: 600;
  margin-right: 20px;
}
</style>